package com.ruoyi.common.utils;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipUtils {

    /**
     * 防止文件重名,将文件按原路径打入压缩包
     * @param paths  待压缩的文件
     * @param destSource 压缩包
     */
    public static void zipWithPath(List<String> paths,String destSource) throws IOException {
        ZipArchiveOutputStream zip = new ZipArchiveOutputStream(new File(destSource));
        for (String file : paths) {
            ZipArchiveEntry entry = new ZipArchiveEntry(file);
            InputStream in = new BufferedInputStream(new FileInputStream(file));
            try {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                zip.putArchiveEntry(entry);
                int c = 0;
                while((c = in.read()) != -1){
                    zip.write(c);
                }
                in.close();
                zip.closeArchiveEntry();
                if (bos != null) {
                    bos.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        zip.flush();
        zip.finish();
    }

    public static void zipFile(List<String> paths,HttpServletResponse response){
        ZipOutputStream zipOutputStream = null;
        try {
            if (CollectionUtils.isEmpty(paths)) {
                return;
            }
            int count = paths.size();
            final CountDownLatch countDownLatch = new CountDownLatch(count);
            ExecutorService pools = Executors.newWorkStealingPool();
            List<TempData> lists = new ArrayList<>(count);
            paths.forEach(p -> {
//                p = p.replaceAll(prefix,piPath);
                WorkCallable workCallable = new WorkCallable(p);
                Future<BufferedInputStream> submit = pools.submit(workCallable);
                countDownLatch.countDown();
                try {
                    TempData tempData = new TempData();
                    tempData.setBis(submit.get());
                    tempData.setPath(p);
                    lists.add(tempData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            if (CollectionUtils.isEmpty(lists)) {
                return;
            }

            //压缩后的zip包名
//            String zipName = LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE) + ".zip";
            String zipName = System.currentTimeMillis()+ ".zip";
//            if (paths.size()==1){
//                zipName= paths.get(0).substring(paths.get(0).lastIndexOf("/")).replaceAll("/","");
//            }
            packageResponse(response, zipName);
            zipOutputStream = new ZipOutputStream(response.getOutputStream());
            zipOutputStream.setMethod(ZipOutputStream.DEFLATED);
            final int BUFFER = 10240;
            for (TempData tempData : lists) {
                try {
                    ZipEntry entry = new ZipEntry(new File(tempData.getPath()).getName());
                    zipOutputStream.putNextEntry(entry);
                    byte[] data = new byte[BUFFER];
                    while ((tempData.getBis().read(data, 0, BUFFER)) != -1) {
                        zipOutputStream.write(data, 0, data.length);
                    }
                } catch (Exception e) {
                    throw e;
                } finally {
                    tempData.getBis().close();
                    tempData.getBis().close();
                    zipOutputStream.flush();
                    zipOutputStream.closeEntry();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != zipOutputStream) {
                try {
                    zipOutputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static void packageResponse(HttpServletResponse response, String zipName) throws UnsupportedEncodingException {
        response.setHeader("content-type", "application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.addHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode((zipName), "utf-8"));
    }

    public static List<Map<String, Object>> unzip(String zipFilePath, String destDir) throws IOException {
        File dir = new File(destDir);
        if (!dir.exists()) {
            boolean mkdirs = dir.mkdirs();
            if (!mkdirs) {
                return null;
            }
        }
        List<Map<String, Object>> mapList = new ArrayList<>();
        //windows下中文默认gbk 正常使用utf-8
        try (ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath), StandardCharsets.UTF_8)) {
            ZipEntry entry = zipIn.getNextEntry();
            while (entry != null) {
                Map<String, Object> map = new HashMap<>();
//                String filePath = destDir + File.separator + entry.getName();
                String filePath = destDir + entry.getName();
                if (!entry.isDirectory()) {
                    extractFile(zipIn, filePath);
                    //添加文件信息
                    map.put("fileSize",new BigDecimal((double) entry.getSize() / (1024 * 1024)).setScale(2, RoundingMode.UP) + "MB") ;
                    map.put("filePath",filePath);
                    map.put("fileName",entry.getName());
                    map.put("fileType",entry.getName().substring(entry.getName().lastIndexOf(".")).split("\\.")[1]);
                    mapList.add(map);
                } else {
                    File dirToCreate = new File(filePath);
                    boolean mkdirs = dirToCreate.mkdirs();
                    if (!mkdirs) {
                        return null;
                    }

                }
                zipIn.closeEntry();
                entry = zipIn.getNextEntry();
            }
        }
        return mapList;
    }

    /**
     * 提取文件
     * @param zipIn ZipInputStream
     * @param filePath 文件路径
     * @throws IOException
     */
    private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            byte[] buffer = new byte[10240];
            int bytesRead;
            while ((bytesRead = zipIn.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
        }
    }
}

class WorkCallable implements Callable<BufferedInputStream> {
    private String path;

    public WorkCallable(String path) {
        this.path = path;
    }

    @Override
    public BufferedInputStream call() throws Exception {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path));
        return bis;
    }
}

class TempData {

    private BufferedInputStream bis;
    //压缩文件的相对路径
    private String path;

    public BufferedInputStream getBis() {
        return bis;
    }

    public void setBis(BufferedInputStream bis) {
        this.bis = bis;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }
}
